import random

import pandas as pd

from .client import BaseSocketClient
from .client import update_last_ack_time
from .parser.std.get_block_info import get_and_parse_block_info
from .parser.std.get_block_info import GetBlockInfo
from .parser.std.get_block_info import GetBlockInfoMeta
from .parser.std.get_company_info_category import GetCompanyInfoCategory
from .parser.std.get_company_info_content import GetCompanyInfoContent
from .parser.std.get_finance_info import GetFinanceInfo
from .parser.std.get_history_minute_time_data import GetHistoryMinuteTimeData
from .parser.std.get_history_transaction_data import GetHistoryTransactionData
from .parser.std.get_index_bars import GetIndexBarsCmd
from .parser.std.get_minute_time_data import GetMinuteTimeData
from .parser.std.get_report_file import GetReportFile
from .parser.std.get_security_bars import GetSecurityBarsCmd
from .parser.std.get_security_count import GetSecurityCountCmd
from .parser.std.get_security_list import GetSecurityList
from .parser.std.get_security_quotes import GetSecurityQuotesCmd
from .parser.std.get_transaction_data import GetTransactionData
from .parser.std.get_xdxr_info import GetXdXrInfo
from .parser.std.setup_commands import SetupCmd1
from .parser.std.setup_commands import SetupCmd2
from .parser.std.setup_commands import SetupCmd3


class TdxHq_API(BaseSocketClient):

    def setup(self):
        """

        """
        SetupCmd1(self.client).call_api()
        SetupCmd2(self.client).call_api()
        SetupCmd3(self.client).call_api()

    # Notice：，如果一个股票当天停牌，那天的K线还是能取到，成交量为0
    @update_last_ack_time
    def get_security_bars(self, category, market, code, start, count):
        """

        :param category:
        :param market:
        :param code:
        :param start:
        :param count:
        :return:
        """
        cmd = GetSecurityBarsCmd(self.client, lock=self.lock)
        cmd.setParams(category, market, code, start, count)

        return cmd.call_api()

    @update_last_ack_time
    def get_index_bars(self, category, market, code, start, count):
        """

        :param category:
        :param market:
        :param code:
        :param start:
        :param count:
        :return:
        """
        cmd = GetIndexBarsCmd(self.client, lock=self.lock)
        cmd.setParams(category, market, code, start, count)

        return cmd.call_api()

    @update_last_ack_time
    def get_security_quotes(self, all_stock, code=None):
        """
        支持三种形式的参数
        get_security_quotes(market, code )
        get_security_quotes((market, code))
        get_security_quotes([(market1, code1), (market2, code2)] )
        :param all_stock （market, code) 的数组
        :param code{optional} code to query
        :return:
        """

        if code is not None:
            all_stock = [(all_stock, code)]
        elif (isinstance(all_stock, list) or isinstance(all_stock, tuple)) and len(all_stock) == 2 and type(all_stock[0]) is int:
            all_stock = [all_stock]

        cmd = GetSecurityQuotesCmd(self.client, lock=self.lock)
        cmd.setParams(all_stock)

        return cmd.call_api()

    @update_last_ack_time
    def get_security_count(self, market):
        """

        :param market:
        :return:
        """
        cmd = GetSecurityCountCmd(self.client, lock=self.lock)
        cmd.setParams(market)

        return cmd.call_api()

    @update_last_ack_time
    def get_security_list(self, market, start):
        """

        :param market:
        :param start:
        :return:
        """
        cmd = GetSecurityList(self.client, lock=self.lock)
        cmd.setParams(market, start)

        return cmd.call_api()

    @update_last_ack_time
    def get_minute_time_data(self, market, code):
        """

        :param market:
        :param code:
        :return:
        """
        cmd = GetMinuteTimeData(self.client, lock=self.lock)
        cmd.setParams(market, code)

        return cmd.call_api()

    @update_last_ack_time
    def get_history_minute_time_data(self, market, code, date):
        """

        :param market:
        :param code:
        :param date:
        :return:
        """
        cmd = GetHistoryMinuteTimeData(self.client, lock=self.lock)
        cmd.setParams(market, code, date)

        return cmd.call_api()

    @update_last_ack_time
    def get_transaction_data(self, market, code, start, count):
        """

        :param market:
        :param code:
        :param start:
        :param count:
        :return:
        """
        cmd = GetTransactionData(self.client, lock=self.lock)
        cmd.setParams(market, code, start, count)

        return cmd.call_api()

    @update_last_ack_time
    def get_history_transaction_data(self, market, code, start, count, date):
        """

        :param market:
        :param code:
        :param start:
        :param count:
        :param date:
        :return:
        """
        cmd = GetHistoryTransactionData(self.client, lock=self.lock)
        cmd.setParams(market, code, start, count, date)

        return cmd.call_api()

    @update_last_ack_time
    def get_company_info_category(self, market, code):
        """

        :param market:
        :param code:
        :return:
        """
        cmd = GetCompanyInfoCategory(self.client, lock=self.lock)
        cmd.setParams(market, code)

        return cmd.call_api()

    @update_last_ack_time
    def get_company_info_content(self, market, code, filename, start, length):
        """

        :param market:
        :param code:
        :param filename:
        :param start:
        :param length:
        :return:
        """
        cmd = GetCompanyInfoContent(self.client, lock=self.lock)
        cmd.setParams(market, code, filename, start, length)

        return cmd.call_api()

    @update_last_ack_time
    def get_xdxr_info(self, market, code):
        """

        :param market:
        :param code:
        :return:
        """
        cmd = GetXdXrInfo(self.client, lock=self.lock)
        cmd.setParams(market, code)

        return cmd.call_api()

    @update_last_ack_time
    def get_finance_info(self, market, code):
        """

        :param market:
        :param code:
        :return:
        """
        cmd = GetFinanceInfo(self.client, lock=self.lock)
        cmd.setParams(market, code)

        return cmd.call_api()

    @update_last_ack_time
    def get_block_info_meta(self, block_file):
        """

        :param block_file:
        :return:
        """
        cmd = GetBlockInfoMeta(self.client, lock=self.lock)
        cmd.setParams(block_file)

        return cmd.call_api()

    @update_last_ack_time
    def get_block_info(self, block_file, start, size):
        """

        :param block_file:
        :param start:
        :param size:
        :return:
        """
        cmd = GetBlockInfo(self.client, lock=self.lock)
        cmd.setParams(block_file, start, size)

        return cmd.call_api()

    def get_and_parse_block_info(self, block_file):
        """

        :param block_file:
        :return:
        """
        return get_and_parse_block_info(self, block_file)

    @update_last_ack_time
    def get_report_file(self, filename, offset):
        """

        :param filename:
        :param offset:
        :return:
        """
        cmd = GetReportFile(self.client, lock=self.lock)
        cmd.setParams(filename, offset)

        return cmd.call_api()

    def get_report_file_by_size(self, filename, filesize=0, reporthook=None):
        """
        Download file from proxy server

        :param reporthook:
        :param filename the filename to download
        :param filesize the filesize to download , if you do not known the actually filesize, leave this value 0
        """
        file_content = bytearray(filesize)

        current_downloaded_size = 0
        get_zero_length_package_times = 0

        while current_downloaded_size < filesize or filesize == 0:
            response = self.get_report_file(filename, current_downloaded_size)

            if response['chunksize'] > 0:
                current_downloaded_size = current_downloaded_size + response['chunksize']
                file_content.extend(response['chunkdata'])

                if reporthook is not None:
                    reporthook(current_downloaded_size, filesize)
            else:
                get_zero_length_package_times = get_zero_length_package_times + 1

                if filesize == 0 or get_zero_length_package_times > 2:
                    break

        return file_content

    def do_heartbeat(self):
        """

        """
        self.get_security_count(random.randint(0, 1))

    def get_k_data(self, code, start_date, end_date):
        """

        :param code:
        :param start_date:
        :param end_date:
        :return:
        """
        # 具体详情参见 https://github.com/rainx/pytdx/issues/5
        # 具体详情参见 https://github.com/rainx/pytdx/issues/21
        def __select_market_code(symbol: str):
            if symbol[0] in ['5', '6', '9'] or symbol[:3] in ['009', '126', '110', '201', '202', '203', '204']:
                return 1

            return 0

        data = pd.concat([self.to_df(self.get_security_bars(9, __select_market_code(code), code, (9 - i) * 800, 800)) for i in range(10)], axis=0)
        data = data.assign(date=data['datetime'].apply(lambda x: str(x)[0:10])).assign(code=str(code))
        data = data.set_index('date', drop=False, inplace=False)
        data = data.drop(['year', 'month', 'day', 'hour', 'minute', 'datetime'], axis=1)[start_date:end_date]

        return data.assign(date=data['date'].apply(lambda x: str(x)[0:10]))
